<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Models\ShopCart;
use Illuminate\Http\Request;


class ShopCartsController extends Controller
{
    /**
     * 购物车列表
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        $user = $request->user();
        $shopCart = ShopCart::with('shop')->select('shop_carts.*', 'shop_carts.id as cart_id')->with([
            'spu.sku',
            'shop'
        ])->where('user_id', $user['id'])->get();
        $data = [];
        foreach ($shopCart as $k => &$v) {
            $data[$v->shop_id]['store_name'] = $v->shop->shop_name;
            $data[$v->shop_id]['list'][] = $v;
        }
        return makeResponse($data, 'success', 200);
    }

    /**
     * 创建购物车
     * @param Request $request
     * @return mixed
     */
    public function create(Request $request)
    {
        $spu_id = $request->input('spu_id');
        $sku_id = $request->input('sku_id');
        $number = $request->input('number');
        $shop_id = $request->input('shop_id');
        $user = $request->user();

        $user_id = $user['id'];
        $check = ShopCart::where(['spu_id' => $spu_id, 'sku_id' => $sku_id, 'user_id' => $user_id])->first();
        if ($check) {
            $check->number += $number;
            $result = $check->save();
        } else {
            $params = compact('spu_id', 'sku_id', 'user_id', 'shop_id','number');
            $result = ShopCart::createOne($params)->save();
        }

        if ($result) {
            return makeResponse([], '添加购物车成功～', 201);
        } else {
            return makeResponse([], '添加购物车失败～', 500);
        }
    }

    /** 删除购物车
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function delete(Request $request, $id)
    {
        $user = $request->user();
        $item = ShopCart::where(['user_id' => $user['id']])->find($id);
        if ($item->delete()) {
            return makeResponse([], '删除成功～', 204);
        } else {
            return makeResponse([], '删除失败～', 500);
        }
    }

    public function add(Request $request)
    {
        $user = $request->user();
        $id = $request->input('id');
        $result = ShopCart::where(['user_id' => $user['id'], 'id' => $id])->increment('number');
        if ($result) {
            return makeResponse([], '操作成功～', 200);
        } else {
            return makeResponse([], '操作失败～', 500);
        }
    }

    public function subtract(Request $request)
    {
        $user = $request->user();
        $id = $request->input('id');
        $result = ShopCart::where(['user_id' => $user['id'], 'id' => $id])->decrement('number');
        if ($result) {
            return makeResponse([], '操作成功～', 200);
        } else {
            return makeResponse([], '操作失败～', 500);
        }
    }

}